var md5 = require('md5.js');
var util = require('util.js');
var valid = require('validate.js');
const app = getApp();
var ApiKey = '38a5d3f2020b0fae2f01065550d26ba7'; //38a5d3f2020b0fae2f01065550d26ba7
var sendRequest = function(url, param, message, success, fail, hideLoading) {
  if (null != param && typeof(param) == "string") {
    hideLoading = fail;
    fail = success;
    success = message;
    message = param;
    param = null;
  } else if (null != param && typeof(param) == "function") {
    hideLoading = success;
    fail = message;
    success = param;
    message = null;
    param = null;
  } else if (null != message && typeof(message) == "function") {
    hideLoading = fail;
    fail = success;
    success = message;
    message = null;
  }
  if (null == hideLoading) {
    hideLoading = true;
  }
  if (null == param) {
    param = new Object();
  }
  param['Fx-Timestamp'] = new Date().getTime();
  var paramStr = ''
  var keys = []
  //参数名排序
  for (var key in param) {
    keys.push(key)
  }
  keys.sort()
  for (var index in keys) {
    var key = keys[index]
    var str = param[key]
    if (null != str && str.length != 0) {
      if (paramStr.length == 0) {
        paramStr = (key + '=' + str)
      } else {
        paramStr = paramStr + '&' + (key + '=' + str)
      }
    } else {
      delete param[key];
    }
  }

  if (paramStr.length == 0) {
    paramStr = ApiKey
  } else {
    paramStr = paramStr + ApiKey
  }

  param.sign = md5.hexMD5(paramStr);

  var header = {}
  if (!param.isJson) {
    header = {
      "Content-Type": "application/x-www-form-urlencoded"
    }
  } else {
    var str = 'Fx-Timestamp' + '=' + param['Fx-Timestamp'] + ApiKey
    var Sign = md5.hexMD5(str)
    header = {
      'Fx-Timestamp': param['Fx-Timestamp'],
      'Fx-Sign': Sign
    }

    param['time'] = new Date().getTime();
    param['Fx-Sign'] = Sign
  }
  console.log(param)
  if (null != message) {
    wx.showLoading({
      title: message,
    })
  }

  wx.request({
    url: url,
    data: param,
    method: 'POST',
    header: header,
    success: function(res) {
      if (res.data.code == 200 && null != success) {
        success(res.data)
      } else if (null != fail) {
        fail(res.data)
      }
    },
    fail: function(res) {
      if (null != fail) {
        fail(res.data)
      }
    },
    complete: function(res) {
      if (null != message && hideLoading) {
        wx.hideLoading()
      }
    }
  })
};
var _busyOpenTimeOutKey = null;

function busyOpen(busyText) {
  if (null == busyText) {
    busyText = "请求中..."
  }
  if (null != _busyOpenTimeOutKey) {
    clearTimeout(_busyOpenTimeOutKey);
  }
  wx.showLoading({
    title: busyText,
  })
}

function busyClose(time) {
  if (null == time || isNaN(parseFloat(time)) || parseFloat(time) <= 0) {
    time = 0;
  } else {
    time = parseFloat(time) * 1000;
  }
  _busyOpenTimeOutKey = setTimeout(function() {
    wx.hideLoading();
  }, time);
}

function _fxTreat(defaultParams, result) {
  var msg = result['msg'];
  var code = result['code'];
  if (code == "2000") {
    if (null != defaultParams.busyText) {
      busyClose();
    }
    util.fxAlert("登录失效，请重新登录", function() {
      if (null != app.loseSessionCallback) {
        app.loseSessionCallback(result);
      }
    });
  } else if (defaultParams.treatType == 0) {
    if (null != defaultParams.callback) {
      defaultParams.callback(result);
    }
  } else if (defaultParams.treatType == 3) {
    if (code == "200") {
      if (null != defaultParams.callback) {
        defaultParams.callback(result);
      }
    } else {
      if (null != defaultParams.busyText) {
        busyClose();
      }
      if (valid.isEmpty(msg)) {
        var msg = code == "200" ? "操作成功" : "操作失败";
      }
      util.fxAlert(msg);
    }

  } else {
    // treatType=2 或者 treatType=1的处理 [Created by 2018-07-20 18:52 fxLDJ]
    if (null != defaultParams.busyText) {
      busyClose();
    }
    if (valid.isEmpty(msg)) {
      var msg = code == "200" ? "操作成功" : "操作失败";
    }
    util.fxAlert(msg, function() {
      if ((defaultParams.treatType == 1 || (defaultParams.treatType == 2 && code == "200")) && null != defaultParams.callback) {
        defaultParams.callback(result);
      }
    });
  }
}
// post [Created by 2018-08-24 13:20 fxLDJ]
var post = function(params) {
  var defaultParams = {
    url: null, // 地址 [Created by 2018-08-18 12:09 fxLDJ]
    requestBody: false, // json请求 [Created by 2018-08-18 12:11 fxLDJ]
    data: null, // 参数 [Created by 2018-08-18 12:09 fxLDJ]
    busyText: null, // 遮罩 [Created by 2018-08-18 12:09 fxLDJ]
    treatType: 3, //返回结果处理方式，0（不进行处理，直接回调），1（为自动提示后回调），2（自动提示，code为200才进行回调）,3（code不等于200才提示 code为200才进行回调）默认为3
    callback: null // 回调 [Created by 2018-08-18 13:35 fxLDJ]
  };
  for (var key in params) {
    var one = params[key];
    if (null != one) {
      defaultParams[key] = one;
    }
  }
  if (null != defaultParams.busyText) {
    busyOpen(defaultParams.busyText);
  }
  var data = defaultParams.data;
  if (null == data) {
    data = new Object();
  }
  var fxTimestamp = new Date().getTime();
  var header = {}
  if (!defaultParams.requestBody) {
    header = {
      "Content-Type": "application/x-www-form-urlencoded"
    }
    data['Fx-Timestamp'] = fxTimestamp;
    var paramStr = '';
    var keys = [];
    //参数名排序
    for (var key in data) {
      keys.push(key)
    }
    keys.sort()
    for (var index in keys) {
      var key = keys[index]
      var str = data[key]
      if (null != str && str.length != 0) {
        if (paramStr.length == 0) {
          paramStr = (key + '=' + str)
        } else {
          paramStr = paramStr + '&' + (key + '=' + str)
        }
      } else {
        delete data[key];
      }
    }

    if (paramStr.length == 0) {
      paramStr = ApiKey
    } else {
      paramStr = paramStr + ApiKey
    }

    data.sign = md5.hexMD5(paramStr);
  } else {
    var str = 'Fx-Timestamp' + '=' + fxTimestamp + ApiKey;
    var Sign = md5.hexMD5(str)
    header = {
      'Fx-Timestamp': fxTimestamp,
      'Fx-Sign': Sign
    }
    // data['time'] = new Date().getTime() ;
    // data['Fx-Sign'] = Sign
  }
  wx.request({
    url: app.data.httpUrl + defaultParams.url,
    data: data,
    method: 'POST',
    header: header,
    success: function(res) {
      _fxTreat(defaultParams, res.data);
    },
    fail: function(res) {
      var result = new Object();
      result['code'] = "9999";
      result['msg'] = "请求错误";
      _fxTreat(defaultParams, result);
    }
  })
};
var postFrom = function(url, params, callback) {
  if (null != params && typeof params == "function") {
    callback = params;
    params = null;
  }
  var params = {
    url: url, // 地址 [Created by 2018-08-18 12:09 fxLDJ]
    data: params, // 参数 [Created by 2018-08-18 12:09 fxLDJ]
    busyText: "请求中", // 遮罩 [Created by 2018-08-18 12:09 fxLDJ]
    treatType: 3, //返回结果处理方式，0（不进行处理，直接回调），1（为自动提示后回调），2（自动提示，code为200才进行回调）,3（code不等于200才提示 code为200才进行回调）默认为3
    callback: function(res) {
      if (null != callback) {
        callback(res);
      }
      busyClose();
    } // 回调 [Created by 2018-08-18 13:35 fxLDJ]
  };
  post(params);
}
var postBody = function(url, params, callback) {
  if (null != params && typeof params == "function") {
    callback = params;
    params = null;
  }
  var params = {
    url: url, // 地址 [Created by 2018-08-18 12:09 fxLDJ]
    requestBody: true, // json请求 [Created by 2018-08-18 12:11 fxLDJ]
    data: params, // 参数 [Created by 2018-08-18 12:09 fxLDJ]
    busyText: "请求中", // 遮罩 [Created by 2018-08-18 12:09 fxLDJ]
    treatType: 3, //返回结果处理方式，0（不进行处理，直接回调），1（为自动提示后回调），2（自动提示，code为200才进行回调）,3（code不等于200才提示 code为200才进行回调）默认为3
    callback: function(res) {
      if (null != callback) {
        callback(res);
      }
      busyClose();
    } // 回调 [Created by 2018-08-18 13:35 fxLDJ]
  };
  post(params);
}
// 文件上传 [Created by 2018-08-21 14:19 fxLDJ]
var fileUpload = function(params) {
  var defaultParams = {
    url: app.data.httpUrl + "v1/upload/pic.json", // 地址 [Created by 2018-08-18 12:09 fxLDJ]
    file: null, // 参数 [Created by 2018-08-18 12:09 fxLDJ]
    busyText: null, // 遮罩 [Created by 2018-08-18 12:09 fxLDJ]
    treatType: 3, //返回结果处理方式，0（不进行处理，直接回调），1（为自动提示后回调），2（自动提示，code为200才进行回调）,3（code不等于200才提示 code为200才进行回调）默认为3
    callback: null // 回调 [Created by 2018-08-18 13:35 fxLDJ]
  };
  for (var key in params) {
    var one = params[key];
    if (null != one) {
      defaultParams[key] = one;
    }
  }
  if (null != defaultParams.busyText) {
    busyOpen(defaultParams.busyText);
  }


  var timestamp = new Date().getTime();
  var str = 'Fx-Timestamp' + '=' + timestamp + ApiKey
  var Sign = md5.hexMD5(str)
  wx.uploadFile({
    url: defaultParams.url,
    method: 'POST',
    filePath: defaultParams.file,
    name: "file",
    header: {
      "Content-Type": "multipart/form-data",
      'Fx-Timestamp': timestamp,
      'Fx-Sign': Sign
    },
    success: function(res) {
      var data = JSON.parse(res.data);
      _fxTreat(defaultParams, data);
    },
    fail: function(res) {
      var result = new Object();
      result['code'] = "9999";
      result['msg'] = "上传错误";
      _fxTreat(defaultParams, result);
    }
  });
};

// 图片上传 [Created by 2018-06-30 09:43 fxLDJ]
var picUpload = function(filePath, success, fail, notLoading) {
  if (null == notLoading) {
    notLoading = false;
  }
  if (!notLoading) {
    wx.showLoading({
      title: '上传中...',
    });
  }

  var timestamp = new Date().getTime();
  var str = 'Fx-Timestamp' + '=' + timestamp + ApiKey
  var Sign = md5.hexMD5(str)
  wx.uploadFile({
    url: app.data.httpUrl + "v1/file/pic.json",
    method: 'POST',
    filePath: filePath,
    name: "file",
    header: {
      "Content-Type": "multipart/form-data",
      'Fx-Timestamp': timestamp,
      'Fx-Sign': Sign
    },
    success: function(res) {
      console.log(res.data)
    },
    fail: function(res) {
      if (null != fail) {
        fail(res);
      }
      if (!notLoading) {
        wx.hideLoading()
      }
    },
    complete: function(res) {
      if (!notLoading) {
        wx.hideLoading()
      }
      if (res.data != undefined) {
        var data = JSON.parse(res.data);
        if (data.code == 200) {
          success(data)
        } else {
          if (null != fail) {
            fail(data);
          }
        }
      } else {
        wx.showToast({
          title: '网络错误',
          icon: 'loading'
        })
      }

    }
  })
};

// 检查登录状态 [Created by 2018-08-13 16:44 fxLDJ]
function checkResult(result, tipsFlag, callback) {

}
module.exports = {
  sendRequest: sendRequest,
  busyOpen: busyOpen,
  busyClose: busyClose,
  post: post,
  postFrom: postFrom,
  postBody: postBody,
  fileUpload: fileUpload,
  picUpload: picUpload
}